package utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

/**
 * Constant network configuration and file names.
 * 
 * @author bh349
 * 
 */
public class ConstantVariables
{
    public final static String IP = "localhost";

    public final static int MALLORY_PORT = 12345;

    public final static int ALICE_PORT = 11111;

    public final static int BOB_PORT = 55555;

    public final static String ALICE_PUBLICKEY = "apub.bin";

    public final static String BOB_PUBLICKEY = "bpub.bin";

    public final static String ALICE_PRIVATEKEY = "apri.bin";

    public final static String BOB_PRIVATEKEY = "bpri.bin";

    public static final String CLIENT_INSTRUCTION = "Enter 11 - Send protocol m1 to target (plain text).\n"
            + "Enter 12 - Send protocol m1 to target in Encrypted Mode.\n"
            + "Enter 21 - Send protocol m2 to target (plain text).\n"
            + "Enter 22 - Send protocol m2 to target in Encrypted Mode.\n"
            + "Enter 31 - Send protocol m3 to target (plain text).\n"
            + "Enter 32 - Send protocol m3 to target in Encrypted Mode.\n"
            + "Enter 41 - Send custom message to target (plain text).\n"
            + "Enter 42 - Send custom message to target in Encrypted Mode.\n";

    /**
     * Get byte array from file.
     * 
     * @param fileName
     * @return
     * @throws IOException
     */
    public static byte[] getBytesFromFile( String fileName ) throws IOException {
        File file = new File( fileName );
        FileInputStream fis = new FileInputStream( fileName );
        byte[] data = new byte[(int) file.length()];
        fis.read( data );
        fis.close();
        return data;
    }

    /**
     * Read public key
     * 
     * @param clientName
     *            "Alice" or "Bob"
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PublicKey getPublicKeyFromFile( String clientName )
            throws IOException, InvalidKeySpecException,
            NoSuchAlgorithmException {
        byte[] encodedKeyBytes;
        if( "Alice".equals( clientName ) ) {
            encodedKeyBytes = ConstantVariables
                    .getBytesFromFile( ConstantVariables.ALICE_PUBLICKEY );
        } else {
            encodedKeyBytes = ConstantVariables
                    .getBytesFromFile( ConstantVariables.BOB_PUBLICKEY );
        }
        return KeyFactory.getInstance( "RSA" ).generatePublic(
                new X509EncodedKeySpec( encodedKeyBytes ) );
    }

}
